package com.zryc.shop.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zryc.shop.cms.entity.PrefrenceAreaProductRelation;
import com.zryc.shop.cms.entity.SubjectProductRelation;
import com.zryc.shop.elasticsearch.ProductRepository;
import com.zryc.shop.pms.entity.*;
import com.zryc.shop.pms.mapper.ProductCategoryMapper;
import com.zryc.shop.pms.mapper.ProductMapper;
import com.zryc.shop.pms.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.lang.Thread.sleep;

/**
 * <p>
 * 商品信息 服务实现类
 * </p>
 *
 * @author zhaozhao
 * @since 2024-01-18
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {


    @Autowired
    private IProductAttributeValueService attributeValueService;

    @Autowired
    private IMemberPriceService memberPriceService;

    @Autowired
    private IProductLadderService ladderService;

    @Autowired
    private IProductFullReductionService fullReductionService;

    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ProductRepository productRepository;


    /**
     * 分页查询商品列表
     *
     * @param keyword           商品名
     * @param pageNum
     * @param pageSize
     * @param publishStatus     上架状态
     * @param verifyStatus      审核状态
     * @param productSn         商品货号
     * @param brandId           商品品牌
     * @param productCategoryId 商品分类
     * @return
     */


//        Page<Product> page = new Page<>(pageNum, pageSize);
//        QueryWrapper<Product> wrapper = new QueryWrapper<>();
//
//        if (!StringUtils.isEmpty(keyword)) {
//            wrapper.like("name", keyword);
//        }
//
//        if (publishStatus != null) {
//            wrapper.eq("publish_status", publishStatus);
//        }
//
//        if (verifyStatus != null) {
//            wrapper.eq("verify_status", verifyStatus);
//        }
//
//        if (productSn != null) {
//            wrapper.eq("product_sn", productSn);
//        }
//
//        if (brandId != null) {
//            wrapper.eq("brand_id", brandId);
//        }
//        if (productCategoryId != null) {
//            wrapper.eq("product_category_id", productCategoryId);
//        }
//
//        return page(page, wrapper);
    @Override
    public Page<Product> list(String keyword, Integer pageNum, Integer pageSize, Integer publishStatus, Integer verifyStatus,
                              String productSn, Long brandId, Long productCategoryId) throws InterruptedException {

        sleep(50);
        // 构建 MyBatis Plus 的分页对象
        Page<Product> page = new Page<>(pageNum, pageSize);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (publishStatus != null) {
            boolQuery.must(QueryBuilders.matchQuery("publishStatus", publishStatus));
        }
        // 添加查询条件
        if (!StringUtils.isEmpty(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("keywords",keyword));
        }

        if (verifyStatus != null) {
            boolQuery.must(QueryBuilders.matchQuery("verifyStatus", verifyStatus));
        }

        if (productSn != null) {
            boolQuery.must(QueryBuilders.matchQuery("productSn", productSn));
        }

        if (brandId != null) {
            boolQuery.must(QueryBuilders.matchQuery("brandId", brandId));
        }

        if (productCategoryId != null) {
            boolQuery.must(QueryBuilders.matchQuery("productCategoryId", productCategoryId));
        }
        builder.withQuery(boolQuery);


        // 执行 Elasticsearch 查询
        builder.withPageable(PageRequest.of(pageNum - 1, pageSize));
        org.springframework.data.domain.Page<Product> search = productRepository.search(builder.build());
        List<Product> productList = search.getContent();
        page.setRecords(productList);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page.setTotal(search.getTotalElements());
        return page;
    }

    /**
     * 更新上架商品状态
     *
     * @param ids
     * @param publishStatus
     * @return
     */
    @Override
    public Object updatePublishStatus(String ids, Integer publishStatus) {
        String[] idList = ids.split(",");
        List<Long> list = Arrays.stream(idList)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        for(Long id : list){
            Optional<Product> optional = productRepository.findById(id);
            if (optional.isPresent()) {
                Product product = optional.get();
                product.setPublishStatus(publishStatus);
                productRepository.save(product);
                baseMapper.updateById(product);
            }
        }
        return null;
    }

    /**
     * 更新商品是否新品状态
     *
     * @param ids
     * @param newStatus
     * @return
     */
    @Override
    public Object updateNewStatus(String ids, Integer newStatus) {
        String[] idList = ids.split(",");
        List<Long> list = Arrays.stream(idList)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        for(Long id : list){
            Optional<Product> optional = productRepository.findById(id);
            if (optional.isPresent()) {
                Product product = optional.get();
                product.setNewStatus(newStatus);
                productRepository.save(product);
                baseMapper.updateById(product);
            }
        }
        return null;
    }

    /**
     * 更新商品是否推荐状态
     *
     * @param ids
     * @param recommendStatus
     * @return
     */
    @Override
    public Object updateRecommendStatus(String ids, Integer recommendStatus) {
        String[] idList = ids.split(",");
        List<Long> list = Arrays.stream(idList)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        for(Long id : list){
            Optional<Product> optional = productRepository.findById(id);
            if (optional.isPresent()) {
                Product product = optional.get();
                product.setRecommandStatus(recommendStatus);
                productRepository.save(product);
                baseMapper.updateById(product);
            }
        }
        return null;
    }

    /**
     * 修改删除状态
     *
     * @param ids
     * @param deleteStatus
     * @return
     */
    @Override
    public Object updateDeleteStatus(String ids, Integer deleteStatus) {
        String[] idList = ids.split(",");
        List<Long> list = Arrays.stream(idList)
                .map(Long::valueOf)
                .collect(Collectors.toList());
        for(Long id : list){
            Optional<Product> optional = productRepository.findById(id);
            if (optional.isPresent()) {
                Product product = optional.get();
                product.setDeleteStatus(deleteStatus);
                productRepository.save(product);
                baseMapper.updateById(product);
            }
        }
        return null;
    }

    /**
     * 查询商品简略信息列表
     *
     * @param keyword
     * @return
     */
    @Override
    public Object simpleList(String keyword) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)) {
            wrapper.like("name", keyword)
                    .or().like("product_sn", keyword);
        }
        return baseMapper.selectList(wrapper);
    }

    /**
     * 新增商品
     *
     * @param product
     * @return
     */
    @Override
    @Transactional
    @SuppressWarnings("all")
    public Object create(Product product) {
        // 1 保存商品信息
        super.save(product);
        // 2 保存商品属性值信息
        List<ProductAttributeValue> productAttributeValueList = product.getProductAttributeValueList();
        productAttributeValueList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        attributeValueService.saveBatch(productAttributeValueList);
        // 3 保存商品会员价格信息
        List<MemberPrice> memberPriceList = product.getMemberPriceList();
        memberPriceList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        memberPriceService.saveBatch(memberPriceList);
        // 4 保存折扣信息
        List<ProductLadder> productLadderList = product.getProductLadderList();
        productLadderList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        ladderService.saveBatch(productLadderList);
        // 5 满减信息
        List<ProductFullReduction> productFullReductionList = product.getProductFullReductionList();
        productFullReductionList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        fullReductionService.saveBatch(productFullReductionList);
        // 6 增加SKU库存信息
        List<SkuStock> skuStockList = product.getSkuStockList();
        String skuCodePrefix = System.currentTimeMillis() + "";
        for (int i = 0; i < skuStockList.size(); i++) {
            skuStockList.get(i).setProductId(product.getId());
            String x = i < 10 ? ("0" + i) : ("" + i);
            skuStockList.get(i).setSkuCode(skuCodePrefix + x);
        }
        skuStockService.saveBatch(skuStockList);
        // 7 更新关联优选中间表
        List<PrefrenceAreaProductRelation> prefrenceAreaProductRelationList = product.getPrefrenceAreaProductRelationList();
        for (PrefrenceAreaProductRelation p : prefrenceAreaProductRelationList) {
            baseMapper.insertPreferenceAreaMid(product.getId(), p.getPrefrenceAreaId());
        }
        // 8 更新关联主题中间表
        List<SubjectProductRelation> subjectProductRelationList = product.getSubjectProductRelationList();
        for (SubjectProductRelation s : subjectProductRelationList) {
            baseMapper.insertSubjectProductMid(product.getId(), s.getSubjectId());
        }
        // 9 更新对应品牌商品数量
        Long brandId = product.getBrandId();
        UpdateWrapper<Brand> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", brandId);
        Brand brand = brandService.getById(brandId);
        Integer productCount = brand.getProductCount();
        updateWrapper.set("product_count", productCount + 1);
        brandService.update(updateWrapper);
        // 10 更新产品分类商品数量
        Long productCategoryId = product.getProductCategoryId();
        ProductCategory productCategory = productCategoryMapper.selectById(productCategoryId);
        productCategory.setProductCount(productCategory.getProductCount() + 1);
        productCategoryMapper.updateById(productCategory);
        do {
            // 找到父类别并将其产品数量加一
            if (productCategory.getParentId() != 0) {
                productCategory = productCategoryMapper.selectById(productCategory.getParentId());
                productCategory.setProductCount(productCategory.getProductCount() + 1);
                // 更新父类别的产品数量
                productCategoryMapper.updateById(productCategory);
            }
        } while (productCategory.getParentId() != 0);
        //  保存商品信息操作日志
        // ProductOperateLog operateLog = new ProductOperateLog();

        productRepository.save(product);
        return "添加商品成功";
    }

    /**
     * 获取当前商品信息
     *
     * @param id
     * @return
     */
    @Override
    public Object selectProductById(Long id) {
        // 1 查询商品表中商品
        Product product = baseMapper.selectById(id);
        // 2 查询商品属性值
        QueryWrapper<ProductAttributeValue> productAttributeValueQueryWrapper = new QueryWrapper<>();
        productAttributeValueQueryWrapper.eq("product_id", id);
        List<ProductAttributeValue> productAttributeValueList = attributeValueService.getBaseMapper().selectList(productAttributeValueQueryWrapper);
        product.setProductAttributeValueList(productAttributeValueList);
        // 3 查询商品会员价格表
        QueryWrapper<MemberPrice> memberPriceQueryWrapper = new QueryWrapper<>();
        memberPriceQueryWrapper.eq("product_id", id);
        List<MemberPrice> memberPriceList = memberPriceService.getBaseMapper().selectList(memberPriceQueryWrapper);
        product.setMemberPriceList(memberPriceList);
        // 4 查询折扣信息表
        QueryWrapper<ProductLadder> productLadderQueryWrapper = new QueryWrapper<>();
        productLadderQueryWrapper.eq("product_id", id);
        List<ProductLadder> productLadderList = ladderService.getBaseMapper().selectList(productLadderQueryWrapper);
        product.setProductLadderList(productLadderList);
        // 5 查询满减信息表
        QueryWrapper<ProductFullReduction> productFullReductionQueryWrapper = new QueryWrapper<>();
        productFullReductionQueryWrapper.eq("product_id", id);
        List<ProductFullReduction> productFullReductionList = fullReductionService.getBaseMapper().selectList(productFullReductionQueryWrapper);
        product.setProductFullReductionList(productFullReductionList);
        // 6 查询sku库存信息
        List<SkuStock> skuStockList = skuStockService.getByProductId(id, "");
        product.setSkuStockList(skuStockList);
        // 7 查询关联优选中间表
        List<PrefrenceAreaProductRelation> prefrenceAreaProductRelationList = baseMapper.getPreferenceAreaMid(id);
        product.setPrefrenceAreaProductRelationList(prefrenceAreaProductRelationList);
        // 8 更新关联主题中间表
        List<SubjectProductRelation> subjectProductRelationList = baseMapper.getSubjectProductMid(id);
        product.setSubjectProductRelationList(subjectProductRelationList);
        return product;
    }

    @Override
    public Object receive(Long productId, Integer productCount) {
        Product product = baseMapper.selectById(productId);
        Integer stock = product.getStock();
        product.setStock(stock+productCount);
        baseMapper.updateById(product);
        return null;
    }

    @Override
    public Object skuStock(Long productId, Integer productCount) {
        List<SkuStock> stocks = skuStockService.getByProductId(productId, "");
        for(SkuStock stock : stocks) {
            stock.setStock(stock.getStock()+productCount);
            skuStockService.updateById(stock);
        }
        return null;
    }

    /**
     * 更新当前商品信息
     *
     * @param id
     * @param product
     * @return
     */
    @Override
    public Object updateProduct(Long id, Product product) {
        // 1.更新商品表
        UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
        productUpdateWrapper.eq("id", id);
        baseMapper.update(product, productUpdateWrapper);
        // 2.更新商品属性值信息
        attributeValueService.removeById(id);
        List<ProductAttributeValue> productAttributeValueList = product.getProductAttributeValueList();
        productAttributeValueList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        attributeValueService.saveBatch(productAttributeValueList);
        // 3.更新商品会员价格信息
        memberPriceService.remove(new QueryWrapper<MemberPrice>().eq("product_id", id));
        List<MemberPrice> memberPriceList = product.getMemberPriceList();
        memberPriceList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        memberPriceService.saveBatch(memberPriceList);
        // 4.更新折扣信息
        ladderService.remove(new QueryWrapper<ProductLadder>().eq("product_id", id));
        List<ProductLadder> productLadderList = product.getProductLadderList();
        productLadderList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        ladderService.saveBatch(productLadderList);
        // 5.更新满减信息
        fullReductionService.remove(new QueryWrapper<ProductFullReduction>().eq("product_id", id));
        List<ProductFullReduction> productFullReductionList = product.getProductFullReductionList();
        productFullReductionList.forEach(item -> {
            item.setProductId(product.getId());// 设置商品id
        });
        fullReductionService.saveBatch(productFullReductionList);
        // 6.更新SKU库存信息
        List<SkuStock> skuStockList = product.getSkuStockList();
        skuStockService.updateBatchById(skuStockList);
        // 7.更新关联优选中间表
        baseMapper.removeFromPrefrence(id);
        List<PrefrenceAreaProductRelation> prefrenceAreaProductRelationList = product.getPrefrenceAreaProductRelationList();
        for (PrefrenceAreaProductRelation p : prefrenceAreaProductRelationList) {
            baseMapper.insertPreferenceAreaMid(product.getId(), p.getPrefrenceAreaId());
        }
        // 8.更新关联主题中间表
        baseMapper.removeFromSubject(id);
        List<SubjectProductRelation> subjectProductRelationList = product.getSubjectProductRelationList();
        for (SubjectProductRelation s : subjectProductRelationList) {
            baseMapper.insertSubjectProductMid(product.getId(), s.getSubjectId());
        }


        return "更新成功";
    }

}
